import {defineStore} from 'pinia'
import {useAddressStore} from './modules/address'

export const useAuthStore = defineStore('auth', {
    state: () => ({
        user: null,
        isAuthenticated: false
    }),
    actions: {
        login(user) {
            this.user = user
            this.isAuthenticated = true
            localStorage.setItem('token', 'dummy-token')
            localStorage.setItem('userId', user.id)
            if (user.isAdmin) {
                localStorage.setItem('isAdmin', 'true')
            }
        },
        logout() {
            this.user = null
            this.isAuthenticated = false
            localStorage.removeItem('token')
            localStorage.removeItem('userId')
            localStorage.removeItem('isAdmin')
        }
    }
})

export const useCartStore = defineStore('cart', {
    state: () => ({
        items: []
    }),
    getters: {
        totalPrice: (state) => {
            return state.items.reduce((total, item) => {
                return total + (item.price * item.quantity)
            }, 0)
        },
        itemCount: (state) => {
            return state.items.reduce((total, item) => {
                return total + item.quantity
            }, 0)
        }
    },
    actions: {
        addToCart(product, quantity = 1) {
            const authStore = useAuthStore()
            if (!authStore.isAuthenticated) {
                throw new Error('请先登录后再添加商品到购物车')
            }

            const existingItem = this.items.find(item => item.id === product.id)
            if (existingItem) {
                existingItem.quantity += quantity
            } else {
                this.items.push({...product, quantity})
            }
        },

        removeFromCart(productId) {
            this.items = this.items.filter(item => item.id !== productId)
        },
        clearCart() {
            this.items = []
        }
    }
})

export const useCategoryStore = defineStore('category', {
    state: () => ({
        categories: [],
        selectedCategory: 'all',
        isLoading: false,
        error: null
    }),
    actions: {
        selectCategory(categorySlug) {
            this.selectedCategory = categorySlug
        },
        async fetchCategories() {
            try {
                this.isLoading = true
                this.error = null

                // 模拟API请求
                const mockCategories = [
                    {id: 1, name: '全部', slug: 'all', icon: '🏠'},
                    {id: 2, name: '电子产品', slug: 'electronics', icon: '🖥️'},
                    {id: 3, name: '服装', slug: 'clothing', icon: '👕'},
                    {id: 4, name: '食品', slug: 'food', icon: '🍎'},
                    {id: 5, name: '图书', slug: 'books', icon: '📚'},
                    {id: 6, name: '运动', slug: 'sports', icon: '⚽'}
                ]

                // 模拟网络延迟
                await new Promise(resolve => setTimeout(resolve, 500))

                this.categories = mockCategories
            } catch (error) {
                this.error = error
                console.error('获取分类失败:', error)
            } finally {
                this.isLoading = false
            }
        }
    },
    getters: {
        getCategoryBySlug: (state) => (slug) => {
            return state.categories.find(c => c.slug === slug)
        }
    }
})

